from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
from utils import decode_predictions_custom
from config import Config

model = load_model(Config.CLASS_MODEL_HOME)


def image_pre(image_path):
    """
    图像分类预测结果
    :param image_path: 图像路径
    :return: 预测的结果
    """
    image = load_img(image_path, target_size=Config.CLASS_TARGET_SIZE)
    # 转为数组
    image = img_to_array(image)
    # 重塑成4D
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # 预测
    predict_result = model.predict(image)
    # 解析预测结果
    label = decode_predictions_custom(predict_result)
    res = []
    for element in label[0]:
        element_ = element[0:len(element) - 1]
        label_result = int("".join(element_))
        score = element[len(element) - 1]
        res.append({"label": label_result, "score": float(score)})
    return res


if __name__ == '__main__':
    print(image_pre("../image/4120073.jpg"))
